<template>
	<view class="e-option" :class="[ns.is('disabled',elDisabled)]" :style="[{height:addUnit(props.height)}]" @tap="handlerClick">
		<text class="e-option__text" :class="[ns.is('active',hasActive)]">{{props.label||props.value}}</text>
	</view>
</template>

<script lang="ts">
	import {defineComponent} from 'vue'
	import mpMixin from "../../libs/mixin/mpMixin";
	
	/**
	 * option 选择器的选项
	 * @description 选择器的选项
	 * @tutorial https://www.uviewui.com/components/select.html
	 * @property {String | Number| Boolean | Object}	value			选项的值
	 * @property {String | Number}			label			选项的标签，若不设置则默认与value相同
	 * @property {Boolean}			disabled				是否禁用 （ 默认 false ）
	 * @property {Object}			customStyle				定义需要用到的外部样式
	 */
	export default defineComponent({
		name: "e-option",
		mixins: [mpMixin],
	});
</script>

<script lang="ts" setup>
	import {
		computed,
		reactive,
		inject,
		toRefs,
		onMounted,
		onBeforeUnmount,
		provide
	} from 'vue'
	import {
		optionProps
	} from "./props";
	import {
		selectContextKey,
		optionContextKey,
		type OptionContext
	} from '../../libs/tokens'
	import {
		useNamespace,
		useDefaultProps
	} from '../../libs/hooks'
	import {
		throwError,
		addUnit
	} from '../../libs/utils/_utils'
	import {
		empty
	} from '../../libs/utils'
	import componentsProps  from "../../libs/config/componentsProps";
	import type {
		 OptionProps
	} from "../../libs/config/propsType";
	
	const {
		option: optionDefaultProps
	} = toRefs(componentsProps);
	
	const _props = defineProps(optionProps)
	
	const props = useDefaultProps < OptionProps> (_props, optionDefaultProps);
	const ns = useNamespace('option')

	const selectContext = inject(selectContextKey)
	if (!selectContext) throwError('EOption', 'e-option需要结合e-select组件使用')
	
	const hasActive = computed(() => selectContext.props.modelValue === props.value.value)

	// 是否禁用，如果父组件e-select禁用的话，将会忽略子组件的配置
	const elDisabled = computed(() => {
		return empty(props.value.disabled) ? empty(selectContext.props.disabled) ? false : selectContext.props.disabled : props
			.value.disabled;
	})

	const handlerClick = () => {
		if (!elDisabled.value) {
			selectContext.optionChange(context)
		}
	}

	const context: OptionContext = reactive({
		props,
	})

	onMounted(() => {
		if (selectContext) {
			selectContext.addField(context)
		}
	})

	onBeforeUnmount(() => {
		selectContext.removeField(context)
	})

	provide(optionContextKey, context)
</script>

<style lang="scss" scoped>
	@import "../../libs/theme/option.scss";
</style>
